package cn.com.darly.vpm.bizapi;

import cn.com.darly.vpm.framework.base.BaseController;
import cn.com.darly.vpm.framework.common.StringDiyUtils;
import cn.com.darly.vpm.framework.common.UuidGenerateUtil;
import cn.com.darly.vpm.security.user.api.UserApi;
import cn.com.darly.vpm.security.user.bean.User;
import cn.com.darly.vpm.security.user.cfg.ApplicationConst;
import cn.com.darly.vpm.security.user.service.UserService;
import com.alibaba.druid.support.http.util.IPAddress;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.ui.ModelMap;
import sun.security.x509.IPAddressName;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import java.util.List;

/**
 * Author : ZhangYuHui
 * Date : 2017/11/13
 * TODO :
 */
@Service
public class UserBiz extends BaseController implements UserApi {

    @Resource
    UserService userService;
    @Override
    public ModelMap forwardLogin() {
        ModelMap model = new ModelMap();
        model.addAttribute(ApplicationConst.getApplicationName(), applicationName);
        model.addAttribute(ApplicationConst.getPageTitle(), "新增用户");
        model.addAttribute(ApplicationConst.getResourceUrl(), resourceUrl);
        model.addAttribute(ApplicationConst.getForwordUrl(),"login/adduser");
        return model;
    }

    @Override
    public ModelMap addUser(User user) {
        ModelMap model = new ModelMap();
        model.addAttribute(ApplicationConst.getApplicationName(), applicationName);
        model.addAttribute(ApplicationConst.getPageTitle(), "用户列表");
        model.addAttribute(ApplicationConst.getResourceUrl(), resourceUrl);
        if (accountExist(user.getAccount())){
            model.addAttribute("message", "用户已存在");
            model.addAttribute(ApplicationConst.getForwordUrl(),"login/userinfo");
        }else {
            user.setId(UuidGenerateUtil.getUUIDLong());
            //对密码进行md5加密
            Md5PasswordEncoder encoder = new Md5PasswordEncoder();
            String pwd = encoder.encodePassword(user.getPwd(), user.getAccount());
            user.setPwd(pwd);
            //对IP控制规则进行赋值
            InetAddress address = getLocalHostLANAddress();
            if (address != null) {
                user.setIprule(address.getHostAddress());
            }
            userService.save(user);
            model.addAttribute("message", "用户添加成功");
            model.addAttribute(ApplicationConst.getForwordUrl(),"login/userinfo");
        }
        return model;
    }

    @Override
    public Boolean accountExist(String account) {
        logger.info("[方法 accountExist]");
        User user = userService.findUserByLoginName(account);
        Boolean returnStr = Boolean.FALSE;
        if (user == null) {
            returnStr = Boolean.TRUE;
        }
        return returnStr;
    }

    //獲取IP地址
    public InetAddress getLocalHostLANAddress() {
        try {
            InetAddress candidateAddress = null;
            // 遍历所有的网络接口
            for (Enumeration ifaces = NetworkInterface.getNetworkInterfaces(); ifaces.hasMoreElements(); ) {
                NetworkInterface iface = (NetworkInterface) ifaces.nextElement();
                // 在所有的接口下再遍历IP
                for (Enumeration inetAddrs = iface.getInetAddresses(); inetAddrs.hasMoreElements(); ) {
                    InetAddress inetAddr = (InetAddress) inetAddrs.nextElement();
                    if (!inetAddr.isLoopbackAddress()) {// 排除loopback类型地址
                        if (inetAddr.isSiteLocalAddress()) {
                            // 如果是site-local地址，就是它了
                            return inetAddr;
                        } else if (candidateAddress == null) {
                            // site-local类型的地址未被发现，先记录候选地址
                            candidateAddress = inetAddr;
                        }
                    }
                }
            }
            if (candidateAddress != null) {
                return candidateAddress;
            }
            // 如果没有发现 non-loopback地址.只能用最次选的方案
            InetAddress jdkSuppliedAddress = InetAddress.getLocalHost();
            return jdkSuppliedAddress;
        } catch (Exception e) {
            return null;
        }
    }
}
